package org.smart4j.chapter1.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * 加载属性文件工具类
 *
 * Created by wangzhen on 2018/3/26.
 */
public class PropsUtil {

    private static final Logger logger = LoggerFactory.getLogger(PropsUtil.class);

    /**
     * 加载属性文件
     *
     * @param fileName
     * @return
     */
    public static Properties loadProps(String fileName) {
        Properties props = null ;
        InputStream is = null ;
        try {
            is = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName) ;
            if(is == null) {
                throw new FileNotFoundException(fileName + "file is not found") ;
            }
            props = new Properties();
            props.load(is);
        } catch (IOException e) {
            logger.error("loading file failure", e);
            e.printStackTrace();
        } finally {
            if(is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    logger.error("closing is failure", e);
                    e.printStackTrace();
                }
            }
        }
        return props;
    }

    public static String getString(Properties props, String key) {
        return getString(props, key, "") ;
    }
    /**
     * 获取字符型属性值，可指定默认值的
     *
     * @param props
     * @param key
     * @param defaultVal
     * @return
     */
    public static String getString(Properties props, String key, String defaultVal) {
        String value = "";
        if(props.containsKey(key)) {
            value = props.getProperty(key, defaultVal);
        }
        return value;
    }

    /**
     *获取整型属性值，可指定默认值
     * @param props
     * @param key
     * @param defaultVal
     * @return
     */
    public static int getInt(Properties props, String key, String defaultVal) {
        String value = getString(props, key, defaultVal);
        return Integer.valueOf(value) ;
    }

    /**
     * 获取整型属性值,默认值0
     * @param props
     * @param key
     * @return
     */
    public static int getInt(Properties props, String key) {
        String value = getString(props, key, "0");
        return Integer.valueOf(value);
    }

    /**
     * 获取布尔型属性值，可指定默认值
     * @param props
     * @param key
     * @return
     */
    public static boolean getBoolean(Properties props, String key, String defaultVal) {
        String value = getString(props, key, defaultVal) ;
        return Boolean.valueOf(value);
    }

    /**
     * 获取布尔型属性值，默认值false
     * @param props
     * @param key
     * @return
     */
    public static boolean getBoolean(Properties props, String key) {
        String value = getString(props, key);
        return Boolean.valueOf(value);
    }
}
